﻿using EventBus.RabbitMQ.Events;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace EventBus.RabbitMQ
{
    public class ConsumerServiceSelector : IConsumerServiceSelector
    {
        private readonly ConcurrentDictionary<string, Type> _serviceSelectorCache = new ConcurrentDictionary<string, Type>();

        public Dictionary<string, List<RouteInfo>> GetServiceInfo()
        {
            var res = new Dictionary<string, List<RouteInfo>>();

            foreach (var service in ServiceCollectionExtensions.HandlerTypeList)
            {
                var attributes = service.GetCustomAttributes(typeof(QueueSubscribeAttribute)).Select(x => x as QueueSubscribeAttribute).ToList();
                attributes.ForEach(x =>
                {
                    if (res.ContainsKey(x.Queue))
                    {
                        res[x.Queue].Add(new RouteInfo
                        {
                            ExchangeName = x.ExchangeName,
                            ExchangeType = x.ExchangeType,
                            RouteKey = x.RouteKey
                        });
                    }
                    else
                    {
                        res.Add(x.Queue, new List<RouteInfo>
                        {
                            new RouteInfo
                            {
                                ExchangeName = x.ExchangeName,
                                ExchangeType = x.ExchangeType,
                                RouteKey = x.RouteKey
                            }
                        });
                        _serviceSelectorCache.TryAdd(x.Queue, service);
                    }
                });
            }
            return res;
        }

        public bool TryGetExecutor(string queueName, out Type type)
        {
            return _serviceSelectorCache.TryGetValue(queueName, out type);
        }
    }
}